# 创建商品评论管理页面
<template>
  <div class="comment-container">
    <!-- 评论趋势图 -->
    <el-card class="trend-card">
      <template #header>
        <div class="card-header">
          <span>评论趋势</span>
          <el-select v-model="trendDays" size="small" @change="fetchCommentTrend">
            <el-option label="最近7天" :value="7" />
            <el-option label="最近30天" :value="30" />
            <el-option label="最近90天" :value="90" />
          </el-select>
        </div>
      </template>
      <div class="trend-chart">
        <v-chart :option="trendOption" autoresize />
      </div>
    </el-card>

    <!-- 评论列表 -->
    <el-card class="comment-list-card">
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <span>评论列表</span>
            <el-button type="primary" link @click="handleExport">
              <el-icon><Download /></el-icon> 导出评论
            </el-button>
          </div>
          <div class="header-right">
            <el-button type="primary" @click="handleBatchReply" :disabled="!selectedComments.length">
              批量回复
            </el-button>
            <el-button type="success" @click="handleManageTemplates">
              <el-icon><Document /></el-icon> 管理模板
            </el-button>
          </div>
        </div>
      </template>

      <el-table
        v-loading="loading"
        :data="commentList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="用户" width="120">
          <template #default="{ row }">
            <div class="user-info">
              <el-avatar :size="30" :src="row.userAvatar">
                {{ row.userName?.charAt(0)?.toUpperCase() }}
              </el-avatar>
              <span>{{ row.userName }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="评分" width="120">
          <template #default="{ row }">
            <el-rate v-model="row.score" disabled show-score />
          </template>
        </el-table-column>
        <el-table-column prop="content" label="评论内容" min-width="200" show-overflow-tooltip />
        <el-table-column prop="createTime" label="评论时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <el-button 
              v-if="!row.reply"
              type="primary" 
              link 
              @click="handleReply(row)"
            >
              回复
            </el-button>
            <span v-else class="text-muted">已回复</span>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 回复对话框 -->
    <el-dialog
      v-model="replyDialogVisible"
      :title="currentComment?.replyContent ? '修改回复' : '回复评论'"
      width="500px"
    >
      <el-form ref="replyFormRef" :model="replyForm" :rules="replyRules">
        <el-form-item label="评论内容" class="comment-content">
          <div class="comment-detail">
            <div class="user-info">
              <el-avatar :size="30" :src="currentComment?.userAvatar">
                {{ currentComment?.userName?.charAt(0)?.toUpperCase() }}
              </el-avatar>
              <span>{{ currentComment?.userName }}</span>
            </div>
            <div class="rating">
              <el-rate v-model="commentScore" disabled show-score />
            </div>
            <div class="content">{{ currentComment?.content }}</div>
            <div class="time">{{ formatDate(currentComment?.createTime) }}</div>
          </div>
        </el-form-item>
        <el-form-item label="回复模板">
          <el-select
            v-model="selectedTemplate"
            placeholder="选择回复模板"
            clearable
            @change="handleTemplateSelect"
          >
            <el-option
              v-for="template in replyTemplates"
              :key="template.id"
              :label="template.name"
              :value="template.content"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="回复内容" prop="reply">
          <el-input
            v-model="replyForm.reply"
            type="textarea"
            :rows="4"
            placeholder="请输入回复内容"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="replyDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitReply">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 批量回复对话框 -->
    <el-dialog
      v-model="batchReplyDialogVisible"
      title="批量回复评论"
      width="500px"
    >
      <el-form ref="batchReplyFormRef" :model="batchReplyForm" :rules="replyRules">
        <el-form-item label="选中评论">
          <div class="selected-count">
            已选择 {{ selectedComments.length }} 条评论
          </div>
        </el-form-item>
        <el-form-item label="回复模板">
          <el-select
            v-model="selectedTemplate"
            placeholder="选择回复模板"
            clearable
            @change="handleTemplateSelect"
          >
            <el-option
              v-for="template in replyTemplates"
              :key="template.id"
              :label="template.name"
              :value="template.content"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="回复内容" prop="reply">
          <el-input
            v-model="batchReplyForm.reply"
            type="textarea"
            :rows="4"
            placeholder="请输入回复内容"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="batchReplyDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitBatchReply">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 模板管理对话框 -->
    <el-dialog
      v-model="templateDialogVisible"
      title="回复模板管理"
      width="800px"
    >
      <div class="template-header">
        <el-button type="primary" @click="handleAddTemplate">
          <el-icon><Plus /></el-icon> 新增模板
        </el-button>
      </div>
      <el-table :data="replyTemplates" style="width: 100%">
        <el-table-column prop="name" label="模板名称" min-width="150" />
        <el-table-column prop="content" label="模板内容" min-width="300" show-overflow-tooltip />
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button-group>
              <el-button type="primary" link @click="handleEditTemplate(row)">
                编辑
              </el-button>
              <el-button type="danger" link @click="handleDeleteTemplate(row)">
                删除
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- 模板编辑对话框 -->
    <el-dialog
      v-model="templateEditDialogVisible"
      :title="currentTemplate.id ? '编辑模板' : '新增模板'"
      width="500px"
    >
      <el-form
        ref="templateFormRef"
        :model="currentTemplate"
        :rules="templateRules"
        label-width="80px"
      >
        <el-form-item label="模板名称" prop="name">
          <el-input v-model="currentTemplate.name" placeholder="请输入模板名称" />
        </el-form-item>
        <el-form-item label="模板类型" prop="type">
          <el-select v-model="currentTemplate.type" placeholder="请选择模板类型">
            <el-option label="普通模板" :value="1" />
            <el-option label="自动回复" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="模板内容" prop="content">
          <el-input
            v-model="currentTemplate.content"
            type="textarea"
            :rows="4"
            placeholder="请输入模板内容"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="templateEditDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitTemplate">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Download, Document, Plus } from '@element-plus/icons-vue'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { LineChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
} from 'echarts/components'
import VChart from 'vue-echarts'
import {
  getProductComments,
  replyComment,
  batchReplyComments,
  getCommentStatistics,
  getCommentTrend,
  exportComments,
  createReplyTemplate,
  updateReplyTemplate,
  deleteReplyTemplate,
  getReplyTemplates
} from '@/api/comment'

// 注册必需的组件
use([
  CanvasRenderer,
  LineChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
])

const route = useRoute()
const productId = computed(() => route.params.id)

// 状态定义
const loading = ref(false)
const commentList = ref([])
const statistics = ref({})
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const selectedComments = ref([])
const trendDays = ref(7)
const replyTemplates = ref([])

// 对话框显示控制
const replyDialogVisible = ref(false)
const batchReplyDialogVisible = ref(false)
const templateDialogVisible = ref(false)
const templateEditDialogVisible = ref(false)

// 当前选中的评论和模板
const currentComment = ref(null)
const currentTemplate = ref({})
const selectedTemplate = ref('')

// 表单数据
const replyForm = ref({ reply: '' })
const batchReplyForm = ref({ reply: '' })
const skuFormRef = ref(null)
const templateFormRef = ref(null)

// 表单校验规则
const replyRules = {
  reply: [
    { required: true, message: '请输入回复内容', trigger: 'blur' },
    { min: 1, max: 500, message: '回复内容长度在 1 到 500 个字符', trigger: 'blur' }
  ]
}

const templateRules = {
  name: [
    { required: true, message: '请输入模板名称', trigger: 'blur' },
    { min: 2, max: 50, message: '模板名称长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择模板类型', trigger: 'change' }
  ],
  content: [
    { required: true, message: '请输入模板内容', trigger: 'blur' },
    { min: 1, max: 500, message: '模板内容长度在 1 到 500 个字符', trigger: 'blur' }
  ]
}

// 获取评论趋势
const fetchCommentTrend = async () => {
  try {
    const res = await getCommentTrend(productId.value, trendDays.value)
    if (res.code === 200 && res.data) {
      // 处理日期格式
      const trendDates = res.data.map(item => {
        const [year, month, day] = item.date
        return `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`
      })

      // 获取每日评论总数
      const trendCounts = res.data.map(item => 
        (item.positiveCount || 0) + (item.negativeCount || 0) + (item.neutralCount || 0)
      )

      // 获取每日好评数
      const positiveCounts = res.data.map(item => item.positiveCount || 0)

      // 更新统计数据
      statistics.value = {
        ...statistics.value,
        trendDates,
        trendCounts,
        positiveCounts
      }
    }
  } catch (error) {
    console.error('获取评论趋势失败:', error)
    ElMessage.error('获取评论趋势失败')
  }
}

// 评论趋势图配置
const trendOption = computed(() => ({
  title: {
    text: '评论趋势'
  },
  tooltip: {
    trigger: 'axis',
    formatter: function(params) {
      const date = params[0].axisValue
      const totalCount = params[0].data
      const positiveCount = params[1].data
      return `${date}<br/>评论数：${totalCount}<br/>好评数：${positiveCount}`
    }
  },
  legend: {
    data: ['评论数', '好评数']
  },
  xAxis: {
    type: 'category',
    data: statistics.value.trendDates || [],
    axisLabel: {
      rotate: 45
    }
  },
  yAxis: {
    type: 'value',
    name: '数量',
    minInterval: 1
  },
  series: [
    {
      name: '评论数',
      type: 'line',
      data: statistics.value.trendCounts || [],
      smooth: true,
      symbol: 'circle',
      symbolSize: 6,
      itemStyle: {
        color: '#409EFF'
      }
    },
    {
      name: '好评数',
      type: 'line',
      data: statistics.value.positiveCounts || [],
      smooth: true,
      symbol: 'circle',
      symbolSize: 6,
      itemStyle: {
        color: '#67C23A'
      }
    }
  ]
}))

// 获取评论列表
const fetchComments = async () => {
  try {
    loading.value = true
    const res = await getProductComments(productId.value, {
      pageNum: currentPage.value,
      pageSize: pageSize.value
    })
    if (res.code === 200) {
      commentList.value = res.data.records || []
      total.value = res.data.total || 0
    }
  } catch (error) {
    console.error('获取评论列表失败:', error)
    ElMessage.error('获取评论列表失败')
  } finally {
    loading.value = false
  }
}

// 获取评论统计
const fetchStatistics = async () => {
  try {
    const res = await getCommentStatistics(productId.value)
    if (res.code === 200) {
      statistics.value = res.data || {}
    }
  } catch (error) {
    console.error('获取评论统计失败:', error)
    ElMessage.error('获取评论统计失败')
  }
}

// 获取回复模板列表
const fetchReplyTemplates = async () => {
  try {
    const res = await getReplyTemplates()
    if (res.code === 200) {
      replyTemplates.value = res.data || []
    }
  } catch (error) {
    console.error('获取回复模板失败:', error)
    ElMessage.error('获取回复模板失败')
  }
}

// 处理评论回复
const handleReply = (row) => {
  currentComment.value = row
  replyForm.value.reply = row.replyContent || ''
  replyDialogVisible.value = true
}

// 提交回复
const submitReply = async () => {
  if (!replyForm.value.reply.trim()) {
    ElMessage.warning('请输入回复内容')
    return
  }

  try {
    await replyComment(currentComment.value.id, replyForm.value.reply)
    ElMessage.success('回复成功')
    replyDialogVisible.value = false
    fetchComments()
  } catch (error) {
    console.error('回复失败:', error)
    ElMessage.error('回复失败')
  }
}

// 处理批量回复
const handleBatchReply = () => {
  if (selectedComments.value.length === 0) {
    ElMessage.warning('请选择要回复的评论')
    return
  }
  batchReplyForm.value.reply = ''
  batchReplyDialogVisible.value = true
}

// 提交批量回复
const submitBatchReply = async () => {
  if (!batchReplyForm.value.reply.trim()) {
    ElMessage.warning('请输入回复内容')
    return
  }

  try {
    await batchReplyComments({
      commentIds: selectedComments.value.map(item => item.id),
      reply: batchReplyForm.value.reply
    })
    ElMessage.success('批量回复成功')
    batchReplyDialogVisible.value = false
    fetchComments()
  } catch (error) {
    console.error('批量回复失败:', error)
    ElMessage.error('批量回复失败')
  }
}

// 导出评论
const handleExport = async () => {
  try {
    const res = await exportComments(productId.value)
    const blob = new Blob([res.data], { type: 'application/vnd.ms-excel' })
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `商品评论-${productId.value}.xlsx`
    link.click()
    window.URL.revokeObjectURL(url)
  } catch (error) {
    console.error('导出评论失败:', error)
    ElMessage.error('导出评论失败')
  }
}

// 模板管理
const handleManageTemplates = () => {
  templateDialogVisible.value = true
  fetchReplyTemplates()
}

// 添加模板
const handleAddTemplate = () => {
  currentTemplate.value = { 
    name: '', 
    content: '',
    type: undefined  // 让用户必须选择类型
  }
  templateEditDialogVisible.value = true
}

// 编辑模板
const handleEditTemplate = (template) => {
  currentTemplate.value = { 
    id: template.id,
    name: template.name,
    content: template.content,
    type: template.type || undefined  // 使用现有类型或让用户选择
  }
  templateEditDialogVisible.value = true
}

// 删除模板
const handleDeleteTemplate = async (template) => {
  try {
    await ElMessageBox.confirm('确定要删除该模板吗？', '提示', {
      type: 'warning'
    })
    await deleteReplyTemplate(template.id)
    ElMessage.success('删除成功')
    fetchReplyTemplates()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除模板失败:', error)
      ElMessage.error('删除模板失败')
    }
  }
}

// 提交模板
const submitTemplate = async () => {
  if (!templateFormRef.value) return
  
  try {
    await templateFormRef.value.validate()
    
    const requestBody = {
      name: currentTemplate.value.name,
      content: currentTemplate.value.content,
      type: currentTemplate.value.type
    }

    if (currentTemplate.value.id) {
      await updateReplyTemplate(currentTemplate.value.id, requestBody)
    } else {
      await createReplyTemplate(requestBody)
    }
    
    ElMessage.success(currentTemplate.value.id ? '更新成功' : '创建成功')
    templateEditDialogVisible.value = false
    fetchReplyTemplates()
  } catch (error) {
    console.error('保存模板失败:', error)
    ElMessage.error(error.response?.data?.message || '保存模板失败')
  }
}

// 选择模板
const handleTemplateSelect = (content) => {
  if (replyDialogVisible.value) {
    replyForm.value.reply = content
  } else if (batchReplyDialogVisible.value) {
    batchReplyForm.value.reply = content
  }
}

// 表格选择变化
const handleSelectionChange = (selection) => {
  selectedComments.value = selection
}

// 分页相关
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  fetchComments()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchComments()
}

// 格式化日期
const formatDate = (dateArray) => {
  if (!dateArray || !Array.isArray(dateArray)) return '暂无'
  const [year, month, day, hour, minute, second] = dateArray
  return `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')} ${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}:${String(second).padStart(2, '0')}`
}

// 评论分数计算属性
const commentScore = computed(() => currentComment.value?.score || 0)

onMounted(() => {
  if (productId.value) {
    fetchComments()
    fetchStatistics()
    fetchCommentTrend()
    fetchReplyTemplates()
  }
})
</script>

<style scoped>
.comment-container {
  padding: 20px;
}

.trend-card {
  margin-bottom: 20px;
}

.trend-chart {
  height: 400px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left,
.header-right {
  display: flex;
  align-items: center;
  gap: 16px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.comment-content {
  margin-bottom: 20px;
}

.comment-detail {
  padding: 16px;
  background-color: var(--el-fill-color-light);
  border-radius: 4px;
}

.comment-detail .rating {
  margin: 8px 0;
}

.comment-detail .content {
  margin: 8px 0;
  color: var(--el-text-color-primary);
}

.comment-detail .time {
  color: var(--el-text-color-secondary);
  font-size: 12px;
}

.selected-count {
  color: var(--el-text-color-secondary);
}

.template-header {
  margin-bottom: 16px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
